package com.fin.zw.aiqas.service;

import com.fin.zw.aiqas.entity.QRuleType;
import com.fin.zw.aiqas.entity.RuleInfo;
import com.fin.zw.aiqas.entity.RuleType;
import com.fin.zw.aiqas.model.request.RuleTypeRequest;
import com.fin.zw.aiqas.model.session.SessionModel;
import com.fin.zw.aiqas.repository.RuleInfoRepository;
import com.fin.zw.aiqas.repository.RuleTypeRepository;
import com.fin.zw.aiqas.util.BadRequestException;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.collections.IteratorUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service("ruleTypeService")
public class RuleTypeService {

    private static final Logger logger = LoggerFactory.getLogger(RuleTypeService.class);

    @Autowired
    private RuleTypeRepository ruleTypeRepository;

    @Autowired
    private RuleInfoRepository ruleInfoRepository;

    /**
     * 创建规则分类
     *
     * @param request
     * @param sessionModel
     */
    public void createRuleType(RuleTypeRequest request, SessionModel sessionModel) {
        RuleType ruleTypeNew = new RuleType();
        BeanUtils.copyProperties(request, ruleTypeNew);
        ruleTypeNew.setOperatorRealName(sessionModel.getUserName());
        ruleTypeNew.setOperatorId(sessionModel.getUserId());
        ruleTypeNew.setCreateTime(new Date());
        ArrayList<RuleType> list = Lists.newArrayList(ruleTypeRepository.findAll(QRuleType.ruleType.name.eq(request.getName())));
        list.forEach(e->{
            if(e.getId().longValue()!= request.getId()) throw new BadRequestException("命名重复", request.getName() + "的规则分类已经存在!");
        });
        ruleTypeRepository.save(ruleTypeNew);
    }

    /**
     * 更新规则分类
     *
     * @param request
     */
    public void updateRuleType(RuleTypeRequest request, SessionModel sessionModel) {
        RuleType ruleType = ruleTypeRepository.findById(request.getId()).orElseThrow(() -> new BadRequestException("", "修改的当前分类信息不存在"));
        ArrayList<RuleType> list = Lists.newArrayList(ruleTypeRepository.findAll(QRuleType.ruleType.name.eq(request.getName())));
        list.forEach(e->{
            if(e.getId().longValue()!= request.getId()) throw new BadRequestException("命名重复", request.getName() + "的规则分类已经存在!");
        });
        BeanUtils.copyProperties(request, ruleType);
        ruleType.setUpdateUserId(sessionModel.getUserId());
        ruleType.setUpdateRealName(sessionModel.getUserName());
        ruleType.setUpdateTime(new Date());
        ruleTypeRepository.save(ruleType);
    }

    /**
     * 根据ID 删除
     *
     * @param id
     */
    public Boolean deleteRuleType(Long id) {
        RuleType ruleType = ruleTypeRepository.findById(id).orElseThrow(() -> new BadRequestException("", "删除的当前分类信息不存在"));
        List<RuleInfo> byRuleTypeId = ruleInfoRepository.findByRuleTypeId(ruleType.getId());
        if (!byRuleTypeId.isEmpty()) {
            logger.info("删除的当前分类信息已被规则信息绑定，请先解绑...");
            return false;
        }
        ruleTypeRepository.delete(ruleType);
        return true;
    }

    /**
     * 分页查询
     *
     * @param pageable
     * @return
     */
    public Page<RuleType> findAll(RuleTypeRequest request, Pageable pageable) {
        BooleanBuilder builder = new BooleanBuilder();
        QRuleType qRuleType = QRuleType.ruleType;
        if (StringUtils.isNotEmpty(request.getName())) {
            builder.and(qRuleType.name.like("%".concat(request.getName().concat("%"))));
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            builder.and(qRuleType.createTime.between(request.getStartTime(), request.getEndTime()));
        }
        Page<RuleType> ruleTypePage = ruleTypeRepository.findAll(builder, pageable);
        Page<RuleType> page = ruleTypePage.map(e -> {//判断该规则分类下面是否有规则
            List<RuleInfo> byRuleTypeId = ruleInfoRepository.findByRuleTypeId(e.getId());
            if (byRuleTypeId != null && byRuleTypeId.size() != 0) {
                e.setHasRule(true);
            } else {
                e.setHasRule(false);
            }
            return e;
        });

        return page;
    }


    /**
     * 列表查询不分页
     *
     * @param request
     * @return
     */

    public List<RuleType> findAll(RuleTypeRequest request) {
        BooleanBuilder builder = new BooleanBuilder();
        QRuleType qRuleType = QRuleType.ruleType;
        if (StringUtils.isNotEmpty(request.getName())) {
            builder.and(qRuleType.name.like("%".concat(request.getName().concat("%"))));
        }
        if (request.getStartTime() != null && request.getEndTime() != null) {
            builder.and(qRuleType.createTime.between(request.getStartTime(), request.getEndTime()));
        }
        Iterator<RuleType> ruleTypeIterator = ruleTypeRepository.findAll(builder).iterator();
        List<RuleType> ruleTypeList = IteratorUtils.toList(ruleTypeIterator);
        return ruleTypeList;
    }

    /**
     * 根据 ID 查询实体
     *
     * @param id
     * @return
     */
    public RuleType fetchById(Long id) {
        RuleType ruleType = ruleTypeRepository.findById(id).orElseThrow(() -> new BadRequestException("", "没有 ID 为 " + id + " 的数据。。。"));
        return ruleType;
    }
}
